<script lang="tsx">
  // 导入Vue相关模块
  import { defineComponent, ref, h, compile, computed } from 'vue';
  // 导入国际化模块
  import { useI18n } from 'vue-i18n';
  // 导入路由相关模块
  import { useRoute, useRouter, RouteRecordRaw } from 'vue-router';
  // 导入路由元信息类型
  import type { RouteMeta } from 'vue-router';
  // 导入应用状态管理模块
  import { useAppStore } from '@/store';
  // 导入路由监听器
  import { listenerRouteChange } from '@/utils/route-listener';
  // 导入打开窗口和正则表达式工具函数
  import { openWindow, regexUrl } from '@/utils';
  // 导入菜单树工具函数
  import useMenuTree from './use-menu-tree';

  export default defineComponent({
    // 定义组件可以触发的自定义事件
    emit: ['collapse'],
    setup() {
      // 使用国际化模块
      const { t } = useI18n();
      // 使用应用状态管理模块
      const appStore = useAppStore();
      // 使用路由器
      const router = useRouter();
      // 使用当前路由
      const route = useRoute();
      // 使用菜单树工具函数
      const { menuTree } = useMenuTree();
      // 定义菜单折叠状态
      const collapsed = computed({
        // 获取菜单折叠状态
        get() {
          if (appStore.device === 'desktop') return appStore.menuCollapse;
          return false;
        },
        // 设置菜单折叠状态
        set(value: boolean) {
          appStore.updateSettings({ menuCollapse: value });
        },
      });

      // 定义菜单展开的key
      const openKeys = ref<string[]>([]);
      // 定义菜单选中的key
      const selectedKey = ref<string[]>([]);

      // 定义跳转函数
      const goto = (item: RouteRecordRaw) => {
        selectedKey.value = [item.name as string]
        router.push({
          name: item.name,
        });
      };
      // 定义查找菜单展开key的函数
      const findMenuOpenKeys = (name: string) => {
        const result: string[] = [];
        let isFind = false;
        const backtrack = (
          item: RouteRecordRaw,
          keys: string[],
          target: string
        ) => {
          if (item.name === target) {
            isFind = true;
            result.push(...keys, item.name as string);
            return;
          }
          if (item.children?.length) {
            item.children.forEach((el) => {
              backtrack(el, [...keys], target);
            });
          }
        };
        menuTree.value.forEach((el: RouteRecordRaw) => {
          if (isFind) return; // Performance optimization
          backtrack(el, [el.name as string], name);
        });
        return result;
      };
      // 监听路由变化
      listenerRouteChange((newRoute) => {
        const { requiresAuth, activeMenu, hideInMenu } = newRoute.meta;
        if ((requiresAuth === true || requiresAuth === false) && (!hideInMenu || activeMenu)) {
          const menuOpenKeys = findMenuOpenKeys(
              (activeMenu || newRoute.name) as string
          );
          const keySet = new Set([...menuOpenKeys, ...openKeys.value]);
          openKeys.value = [...keySet];
          selectedKey.value = [
            activeMenu || menuOpenKeys[menuOpenKeys.length - 1],
          ];
        }
      }, true); 
      // 定义设置菜单折叠状态的函数
      const setCollapse = (val: boolean) => {
        if (appStore.device === 'desktop')
          appStore.updateSettings({ menuCollapse: val });
      };
      // 定义渲染子菜单的函数
      const renderSubMenu = () => {
        function travel(_route: RouteRecordRaw[], nodes = []) {
          if (_route) {
            _route.forEach((element) => {
              // This is demo, modify nodes as needed
              const icon = element?.meta?.icon
                ? () => h(compile(`<${element?.meta?.icon}/>`))
                : null;
              const node =
                element?.children && element?.children.length !== 0 ? (
                  <a-sub-menu
                    key={element?.name}
                    v-slots={{
                      icon,
                      title: () => h(compile(t(element?.meta?.locale || ''))),
                    }}
                  >
                    {travel(element?.children)}
                  </a-sub-menu>
                ) : (
                  <a-menu-item
                    key={element?.name}
                    v-slots={{ icon }}
                    onClick={() => goto(element)}
                  >
                    {t(element?.meta?.locale || '')}
                  </a-menu-item>
                );
              nodes.push(node as never);
            });
          }
          return nodes;
        }
        return travel(menuTree.value);
      };

      // 返回渲染函数
      return () => (
        <a-menu
          v-model:collapsed={collapsed.value}
          v-model:open-keys={openKeys.value}
          show-collapse-button={appStore.device !== 'mobile'}
          auto-open={false}
          selected-keys={selectedKey.value}
          auto-open-selected={true}
          level-indent={34}
          style="height: 100%"
          onCollapse={setCollapse}
        >
          {renderSubMenu()}
        </a-menu>
      );
    },
  });
</script>

<style lang="less" scoped>
  // 深度选择器，用于修改子组件样式
  :deep(.arco-menu-inner) {
    // 修改菜单头部样式
    .arco-menu-inline-header {
      display: flex;
      align-items: center;
    }
    // 修改图标样式
    .arco-icon {
      &:not(.arco-icon-down) {
        font-size: 18px;
      }
    }
  }
</style>
